﻿using System;
using System.Web.Mvc;
using PagedList;
using AutoMapper;
using System.Threading.Tasks;
using System.Linq;
using BBICMS.WebUI.Filters;
using BBICMS.Repository;
using BBICMS.Model.ViewModel.Identity;
using BBICMS.Infrastructure.Configs;
using BBICMS.Model.Security;
using BBICMS.ViewModel;
using System.Web;
using System.Web.Security;
using Newtonsoft.Json;
using BBICMS.ViewModel.Identity;
using BBICMS.Resources;
using BBICMS.Application.ViewModels;

namespace BBICMS.WebUI.Areas.Admin.Controllers
{
    [SIGAuth]
    public class UserController : BaseController  {

      
        public ActionResult Index(int? page, DateTime? startDate, DateTime? endDate, string userName)
        {
            var userListVM = new UserListVM
            {
                StartDate = startDate,
                EndDate = endDate,
                Username = userName,           
                PageIndex = (page ?? 1) - 1,
                PageSize = SettingsManager.User.PageSize,
                SetPasswordVM = new SetPasswordVM()
            };

            userListVM.Users = _unit.Users.SearchUsers(userListVM.PageIndex, userListVM.PageSize, userListVM.Username,
                userListVM.StartDate, userListVM.EndDate);
            userListVM.TotalUserCount = _unit.Users.SearchUsersCount(userListVM.Username, userListVM.StartDate, userListVM.EndDate);

            var usersAsIPagedList = new StaticPagedList<User>(userListVM.Users, userListVM.PageIndex + 1, userListVM.PageSize, userListVM.TotalUserCount);
            ViewBag.OnePageOfUsers = usersAsIPagedList;          

            return View(userListVM);

        }

        // GET: User/Details/5
        [HttpGet]
        public ActionResult Details(Guid id)
        {
            //if (id == null)
            //{
            //    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            //}
            User user = _unit.Users.GetById(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return PartialView("_Detail",user);
        }

        // GET: User/Create
        public ActionResult Create()
        {
            RegisterVM vm = new RegisterVM();
            return PartialView("_UserCreate", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Create(RegisterVM model)
        {
            if (!ModelState.IsValid)
            {
                var errorMes = GetModelErrorMessage();
                AR.Setfailure(errorMes);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

          
                var result = _unit.Users.Register(model);


            if (result == 1)
            {
                AR.Setfailure(Messages.CannotRegisterEmail);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            if (result == 2)
            {
                AR.Setfailure(Messages.CannotRegisterUserName);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


            AR.SetSuccess(string.Format(Messages.AlertCreateSuccess, EntityNames.User));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        public async Task<JsonResult> IsUserNameUnique(string UserName)
        {
            var user = await _unit.Users.GetUserByName(UserName);

            return user == null
                ? Json(true, JsonRequestBehavior.AllowGet)
                : Json(false, JsonRequestBehavior.AllowGet);
        }

        public async Task<JsonResult> IsEmailUnique(string Email)
        {
            var user = await _unit.Users.GetUserByEmail(Email);

            return user == null
                ? Json(true, JsonRequestBehavior.AllowGet)
                : Json(false, JsonRequestBehavior.AllowGet);
        }

        // GET: Users/Edit/5
        public ActionResult Edit(Guid? id)
        {
            EditProfileVM Profiles = new EditProfileVM();
            if (id == null)
            {               
                return PartialView("_UserEdit", Profiles);
            }
            var user = _unit.Users.GetById(id);
            if (user == null)
            {
                return HttpNotFound();
            }

         
            Profiles = Mapper.Map<EditProfileVM>(user);
            return PartialView("_UserEdit", Profiles);
            
        }

        // POST: Users/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Edit([Bind(Include = "Id,Email,RealName,Birthday,IsActive,Gender,QQ,Mobile")] EditProfileVM profile)
        {
            if (!ModelState.IsValid)
            {
                var errorMes = GetModelErrorMessage();
                AR.Setfailure(errorMes);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var user = _unit.Users.GetById(profile.Id);
            if (user == null)
            {
                AR.Setfailure("不存在此用户！");
                return Json(AR, JsonRequestBehavior.DenyGet);
               // return Json(false, JsonRequestBehavior.DenyGet);
            }
            try
            {
                user.Email = profile.Email;
                user.RealName = profile.RealName;
                user.IsActive = profile.IsActive;
                //user.DepartmentId = profile.DepartmentId;
                //user.PositionId = profile.PositionId;
                user.QQ = profile.QQ;
                user.Mobile = profile.Mobile;
                user.Gender = profile.Gender;
                user.Birthday = profile.Birthday;

                _unit.Users.Update(user);
                _unit.SaveChanges();

                AR.SetSuccess("操作成功！");
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch(Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }
        public JsonResult IsEmailUniqueAtEdit(string email, Guid id)
        {
            var result = _unit.Users.IsEmailUniqueAtEdit(email, id);

            return result
                ? Json(true, JsonRequestBehavior.AllowGet)
                : Json(false, JsonRequestBehavior.AllowGet);
        }


        [HttpGet]
        public PartialViewResult SetRole(Guid id)
        {
          
            var user = _unit.Users.GetById(id);
            SetUserRoles vm = new SetUserRoles
            {
                UserId = id,
                RoleIds = user.Roles.Select(r=>r.Id).ToArray(),
                Roles = _unit.Roles.GetAll().Where(r=>r.Id!=SettingsManager.Role.Founder)
            };
            
            return PartialView("_SetRole", vm);
        }


        [HttpPost]
        public JsonResult SetRole(Guid UserId, int[] RoleId)
        {
            try
            {
                var user = _unit.Users.GetFirstOrDefault((u=>u.Id == UserId),(u=>u.Roles));

                var isHasFounder = user.Roles.Contains(_unit.Roles.GetById(SettingsManager.Role.Founder));
                var roles = isHasFounder ? _unit.Roles.FindBy(r => RoleId.Contains(r.Id) || r.Id == SettingsManager.Role.Founder) : _unit.Roles.FindBy(r => RoleId.Contains(r.Id));
                user.Roles.Clear();
                foreach (Role r in roles)
                {
                    user.Roles.Add(r);
                }

                _unit.Users.Update(user);
                _unit.SaveChanges();

                if (User.UserId == user.Id)
                {
                    var userRoles = user.Roles.Select(m => m.RoleName).ToArray();

                    CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
                    serializeModel.UserId = user.Id;
                    serializeModel.RealName = user.RealName;
                    serializeModel.Avatar = string.IsNullOrEmpty(user.PhotoUrl) ? SettingsManager.User.DefaultAvatar : user.PhotoUrl;
                    serializeModel.Roles = userRoles;
                    //serializeModel.Menus = GetUserMenus(user.);

                    TimeSpan timeout = FormsAuthentication.Timeout;
                    DateTime expire = DateTime.Now.Add(timeout);


                    string userData = JsonConvert.SerializeObject(serializeModel, Formatting.Indented,
                        new JsonSerializerSettings()
                        {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        });


                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                             1,
                             user.UserName,
                             DateTime.Now,
                             expire,
                             true,
                             userData);

                    string encTicket = FormsAuthentication.Encrypt(authTicket);
                    HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                    Response.Cookies.Add(faCookie);
                }
                   // _userService.SetUserCookies(true, user);

                AR.SetSuccess("设置成功");
                return Json(AR, JsonRequestBehavior.DenyGet);
            }catch(Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }          


        }

        [HttpGet]
        public ActionResult SetPassword(Guid id)
        {
            SetPasswordVM model = new SetPasswordVM
            {
                UserId = id
            };           
            return PartialView("_SetPassword",model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult SetPassword(SetPasswordVM model)
        {
            if (!ModelState.IsValid)
            {
                var errorMes = GetModelErrorMessage();
                AR.Setfailure(errorMes);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            
            var result = _unit.Users.SetPassword(model.UserId, model.NewPassword);
            _unit.SaveChanges();

            if (result)
            {
                AR.SetSuccess("重设成功");
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            AR.Setfailure("重设失败");
            return Json(AR, JsonRequestBehavior.DenyGet);
          
        }


        [HttpPost]
        public JsonResult IsActive(Guid id)
        {
            var user = _unit.Users.GetById(id);
            if (user != null)
            {
                user.IsActive = !user.IsActive;
                _unit.Users.Update(user);
                _unit.SaveChanges();

                AR.SetSuccess("设置成功");
                return Json(AR, JsonRequestBehavior.DenyGet);              

            }
            AR.Setfailure("设置失败");
            return Json(AR, JsonRequestBehavior.DenyGet);
           
        }


        
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(Guid id)
        {
            User user = _unit.Users.GetById(id);  
           
            if (user == null)
            {               
                AR.Setfailure("未找到此用户！");
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            if (user.Id.ToString() == SettingsManager.User.Founder)
            {
                AR.Status = Model.Enums.Status.Warning;
                AR.Setfailure("创始人帐号，不可以删除！");             
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _unit.Users.Delete(user);
            _unit.SaveChanges();
            return Json(AR, JsonRequestBehavior.DenyGet);
          
        }

        protected override void Dispose(bool disposing)
        {
            this._unit.Dispose();
            base.Dispose(disposing);
        }


    }
}